/**	
 * <br>
 * Copyright 2011 Chuan. All rights reserved.<br>
 * <br>			 
 * Package: com.chuan.mantu.service <br>
 * FileName: NetPicService.java <br>
 * <br>
 * @version
 * @author javacyc@qq.com
 * @created 2012-11-20
 * @last Modified 
 * @history
 */

package com.chuan.mantu.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.chuan.mantu.utils.Const;
import com.chuan.mantu.utils.FileUtil;
import com.chuan.mantu.utils.ShareObj;
import com.chuan.mantu.vo.Pic;
import com.chuan.mantu.vo.PicRecord;

/**
 * {更新图片数据Service}
 *  
 *  @author javacyc@qq.com
 *  @created 2012-11-20 上午10:36:18
 *  @lastModified       
 *  @history           
 */

public class NetPicService {

	/**
	 * 
	 *  ｛从网络下载图片存到file目录下｝
	 *  @param context
	 *  @param file 存放目录
	 *  @param category 类别
	 *  @return ArrayList<Pic> 下载完成的图片集合 
	 *  @author javacyc@qq.com
	 *  @created 2012-11-20 下午01:58:16
	 *  @lastModified       
	 *  @history
	 */
	public static ArrayList<Pic> updatePicList(Context context, File file, String category) {
		ArrayList<Pic> lp = new ArrayList<Pic>();
//		http://localhost:8000/brm/getDownPics.do?downCount=10&pictype=1&deviceId=xxxxx
		StringBuffer url = new StringBuffer(128);
		TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		url.append(Const.DOWNLOAD_PICS_URL);
		url.append("downCount=").append(Const.PIC_DISPLAY_NUM);
		url.append("&pictype=").append(category);
		url.append("&deviceId=").append(tm.getDeviceId());
		HttpPost request = new HttpPost(url.toString());
		try {
			HttpResponse response = new DefaultHttpClient().execute(request);
			String json = EntityUtils.toString(response.getEntity());//Json字符串
			JSONArray array = new JSONArray(json);
			if(array.length() == 0){
				Log.d(Const.DEBUG, "Json is empty");
			}else{
				for(int i = 0; i < array.length(); i++){
					String picname = new String(array.optString(i).getBytes());
//					http://localhost:8000/brm/getPicById.do?picid=1&deviceid=1
					url.setLength(0);
					url.append(Const.DOWNLOAD_PIC_URL);
					url.append("picid=").append(FileUtil.getPicId(picname));
					url.append("&deviceid=").append(tm.getDeviceId());
					if(downPic(url.toString(),category,picname)){
							Pic pic = new Pic();
							pic.setName(picname);
							lp.add(pic);
							if(i == 0){
								//记录下加载的最小一张图片相关信息
								PicRecord pr = new PicRecord();
								pr.setMinPid(FileUtil.getPicId(pic.getName()));
								ShareObj.INSTANCE.getPicRecordMap().put(category, pr);
							}
							if(i == (array.length() - 1)){
								//记录下加载的最大一张图片相关信息
								ShareObj.INSTANCE.getPicRecordMap().get(category).setMaxPid(FileUtil.getPicId(pic.getName()));
							}
						}
					}
				}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return lp;
	}

	
	/**
	 * 
	 *  ｛下载单个图片到具体目录下｝
	 *  @param url 下载地址
	 *  @param category 类别目录
	 *  @param picname 图片名称
	 *  @return
	 *  @author javacyc@qq.com
	 *  @created 2012-12-20 上午10:48:04
	 *  @lastModified       
	 *  @history
	 */
	public static boolean downPic(String url, String category, String picname){
		try {
			URL downurl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection)downurl.openConnection();
			conn.setRequestMethod("GET");
//			//如果运行超过5秒会自动失效 这是android规定
			conn.setConnectTimeout(5 * 1000);
			conn.setDoInput(true);
			//获取长度
			int length = (int) conn.getContentLength();
			if (length != -1 && conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();
				File myCaptureFile = new File(Const.PIC_DOWNLOAD_ROOT_PATH + category + Const.PATH_BACKLASH + picname);    
				FileOutputStream fos = new FileOutputStream(myCaptureFile);
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					fos.write(buffer, 0, len);
				}
				is.close();
				fos.close();
				is.close();
				conn.disconnect();
		    	return true;
			}else{
				conn.disconnect();
				return false;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} 		
		return false;
	} 
	
}